package com.gaff.emp.core.modules.perm.controller.dept;

import com.gaff.emp.core.EmpException;
import com.gaff.emp.core.R;
import com.gaff.emp.core.modules.auth.annotation.Auth;
import com.gaff.emp.core.modules.perm.controller.dept.form.CreateForm;
import com.gaff.emp.core.modules.perm.controller.dept.form.DeleteForm;
import com.gaff.emp.core.modules.perm.controller.dept.form.UpdateForm;
import com.gaff.emp.core.modules.perm.entity.SysDept;
import com.gaff.emp.core.modules.perm.service.SysDeptService;
import com.gaff.emp.core.syslog.annotation.SysOperaLog;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;


@Slf4j
@RestController
@RequestMapping("/sys/dept")
public class SysDeptController {

    @Autowired
    private SysDeptService sysDeptService;

    @GetMapping("/all")
    @ApiOperation("获取全部部门列表")
    @SysOperaLog(value = "获取全部部门列表", isPersistence = false)
    @Auth(perm = "dept")
    public R all() {
        return R.ok(sysDeptService.queryAllDepts());
    }


    @PostMapping("/create")
    @ApiOperation("新增部门")
    @SysOperaLog(value = "新增部门")
    @Auth(perm = "dept")
    public R create(@RequestBody @Valid CreateForm form, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            throw new IllegalArgumentException(bindingResult.getFieldError().getDefaultMessage());
        }
        sysDeptService.createDept(form);
        return R.ok();
    }

    @GetMapping("/info/{id}")
    @ApiOperation("获取部门信息")
    @SysOperaLog(value = "获取部门信息", isPersistence = false)
    @Auth(perm = "dept")
    public R info(@PathVariable("id") Integer id) {
        SysDept dept = sysDeptService.queryDeptById(id);
        if (dept == null) {
            throw new EmpException("部门不存在");
        }
        return R.ok(dept);
    }

    @PostMapping("/update")
    @ApiOperation("更新部门")
    @SysOperaLog(value = "更新部门")
    @Auth(perm = "dept")
    public R update(@RequestBody @Valid UpdateForm form, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            throw new IllegalArgumentException(bindingResult.getFieldError().getDefaultMessage());
        }
        sysDeptService.updateDept(form);
        return R.ok();
    }

    @PostMapping("/delete")
    @ApiOperation("删除部门")
    @SysOperaLog(value = "删除部门")
    @Auth(perm = "dept")
    public R delete(@RequestBody @Valid DeleteForm form, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            throw new IllegalArgumentException(bindingResult.getFieldError().getDefaultMessage());
        }
        sysDeptService.deleteById(form.getId());
        return R.ok();
    }

}
